package indi.yangshenhui.hbase.dao.util;

import indi.yangshenhui.hbase.dao.exception.HBaseDaoException;
import indi.yangshenhui.tool.ObjectUtil;

import java.util.Date;

import org.apache.hadoop.hbase.util.Bytes;

/**
 * 
 * @author yangshenhui
 */
public class TypeUtil {

	/**
	 * 字节数字转换成Object
	 * 
	 * @param value
	 *            字节数组(
	 *            该字节数组必须由String转换而来否则报NumberFormatException因为put到HBase时候的字节数组由String转换而来
	 *            )
	 * @param clazz
	 * @return
	 * @throws HBaseDaoException
	 */
	public static Object transform(byte[] value, Class<?> clazz)
			throws HBaseDaoException {
		if (ObjectUtil.isNull(value) || ObjectUtil.isNull(clazz)) {
			return null;
		}
		try {
			if (int.class == clazz || Integer.class == clazz) {
				return Integer.parseInt(Bytes.toString(value));
			} else if (float.class == clazz || Float.class == clazz) {
				return Float.parseFloat(Bytes.toString(value));
			} else if (double.class == clazz || Double.class == clazz) {
				return Double.parseDouble(Bytes.toString(value));
			} else if (long.class == clazz || Long.class == clazz) {
				return Long.parseLong(Bytes.toString(value));
			} else if (short.class == clazz || Short.class == clazz) {
				return Short.parseShort(Bytes.toString(value));
			} else if (char.class == clazz || Character.class == clazz) {
				return value.length == 1 ? Bytes.toString(value).charAt(0)
						: null;
			} else if (byte.class == clazz || Byte.class == clazz) {
				return Byte.parseByte(Bytes.toString(value));
			} else if (boolean.class == clazz || Boolean.class == clazz) {
				return Boolean.parseBoolean(Bytes.toString(value));
			} else if (String.class == clazz) {
				return Bytes.toString(value);
			} else if (Date.class == clazz) {
				return new Date(Long.parseLong(Bytes.toString(value)));
			}
		} catch (NumberFormatException e) {
			throw new HBaseDaoException(e);
		}
		return null;
	}

	private TypeUtil() {
	}

}